package com.hangzhou.xyj.ui.activity;

import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.manager.ScreenManager;
import com.hangzhou.xyj.model.RecordModel;
import com.hangzhou.xyj.ui.dialog.TipsDialog;
import com.hangzhou.xyj.ui.widget.views.MyImageView;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.ToastUtil;
import com.mediaideas.videoengine.recorder.AudioRecorder;
import com.mediaideas.videoengine.recorder.AudioRecorderBuilder;
import com.mediaideas.videoengine.utils.FileUtils;
import com.mediaideas.videoengine.utils.MusicUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 清唱界面
 * <p/>
 * Created by Administrator on 2016/1/27.
 */
public class SingAloneActivity extends BasePlayActivity implements View.OnClickListener {
    protected final static long MAX_DURATION = 5 * 60 * 1000; // 录音最大时间5m
    protected MyImageView mBtnStartRecorder;
    protected MyTextView mBtnFinishedRecorder;
    protected ProgressBar mProgressBar;
    protected AudioRecorder mAudioRecorder;
    protected String mRecordFilePath;
    protected Timer mTimer;
    protected TimerTask mTimerTask;
    protected long mProgressTime = 0;
    protected MyImageView mShowRecordingImgView;
    protected RelativeLayout mRlBack;//返回键
    protected RelativeLayout mRlFinish;//结束按钮
    private boolean isFirst = true;

    @Override
    public void initDatas() {
        final XYJApplication application = XYJApplication.getApplication(this);
        mAudioRecorder = application.getRecorder();
        if (mAudioRecorder == null || mAudioRecorder.getStatus() == AudioRecorder.Status.STATUS_UNKNOWN) {
            mAudioRecorder = AudioRecorderBuilder.with(application)
                    .fileName(FileUtils.getNextSoundFileName(this))
                    .config(AudioRecorder.MediaRecorderConfig.DEFAULT)
                    .loggable()
                    .build();
            application.setRecorder(mAudioRecorder);
        }
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_sing_alone);
    }

    @Override
    public void initListeners() {
        mRlBack.setOnClickListener(this);
        mRlFinish.setOnClickListener(this);
        mBtnStartRecorder.setOnClickListener(this);
    }

    @Override
    public void initTop() {
        enableTop(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioRecorder.isRecording()) {
            mAudioRecorder.cancel();
        }
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    @Override
    public void initViews() {
        mRlBack = findView(R.id.rl_back_area);
        mRlFinish = (RelativeLayout) findViewById(R.id.rl_finish_area);
        mShowRecordingImgView = (MyImageView) findViewById(R.id.show_recording_img_view);
        mBtnFinishedRecorder = (MyTextView) findViewById(R.id.btn_finished_recorder);
        mCurrentTime = (MyTextView) findViewById(R.id.tv_play_current_time);
        mAudioDuration = (MyTextView) findViewById(R.id.tv_play_total_time);
        mBtnStartRecorder = (MyImageView) findViewById(R.id.btn_start_record);
        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back_area://点击返回按钮
                showQuitDialog();
                break;
            case R.id.rl_finish_area://点击结束按钮
                stopAudioRecorder();
                break;
            case R.id.btn_start_record://点击录制按钮
                //没有录制：开启录制
                if (!mAudioRecorder.isRecording()) {
                    startAudioRecorder();
                } else {
                    pauseAudioRecorder();
                }
                break;
        }
    }

    /**
     * 退出前 弹出框
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/5/20 14:14
     */
    public void showQuitDialog() {
        if (mAudioRecorder.isRecording()) {
            TipsDialog dialog = new TipsDialog(mContext, "提示", "退出前是否保存？", "保存", "不保存") {
                @Override
                protected void OnClickNegativeButton() {
                    ScreenManager.getInstance().currentActivity().finish();
                }

                @Override
                protected boolean OnClickPositiveButton() {
                    stopAudioRecorder();
//                    if (mRecordFilePath != null && FileUtils.isFileExists(mRecordFilePath)) {
//                        showPreviewRecordPage(mRecordFilePath);
//                    } else {
//                        ToastUtil.show("您还未启动录制哦!");
//                    }
                    return true;
                }
            };
            dialog.setCancel(true);
            dialog.show();
        } else {
            ScreenManager.getInstance().currentActivity().finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {//按了 返回键
            showQuitDialog();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 跳转到预览界面
     *
     * @param path
     */
    protected void showPreviewRecordPage(String path) {
        RecordModel record = new RecordModel();
        record.setUserId(XYJApplication.getUserInfo().getUserId()); //设置用户id
        record.setMixerFilePath(path); //录音文件只有本地混音路径，其他都为空
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            record.setDuration(mediaPlayer.getDuration());//设置录音时长
            mediaPlayer.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
        record.setCreateTime(System.currentTimeMillis());//设置戏曲创建时间
        IntentManager.getInstance().goPreviewRecordActivity(mContext, record);
        closeActivity();
    }

    /**
     * 开启录制
     */
    protected void startAudioRecorder() {
        if (isFirst) {
            isFirst = false; //仅执行一次
            mAudioRecorder.deleteTempRecordDir();//删除缓存文件
        }
        mAudioRecorder.start(new AudioRecorder.OnStartListener() {
            @Override
            public void onStarted() {
//                mShowRecordingImgView.setVisibility(View.VISIBLE);
//                mShowRecordingImgView.setBackgroundResource(R.drawable.recording_animation);
                if (mShowRecordingImgView.getBackground() != null && mShowRecordingImgView.getBackground() instanceof AnimationDrawable) {
                    AnimationDrawable animationDrawable = (AnimationDrawable) mShowRecordingImgView.getBackground();
                    animationDrawable.start();
                }
                setAudioRecorderBtnStatus(mAudioRecorder.getStatus());
                if (mTimer != null) {
                    mTimer.cancel();
                    mTimer = null;
                }
                if (mTimerTask != null) {
                    mTimerTask.cancel();
                    mTimerTask = null;
                }
                restartTime();
            }

            @Override
            public void onException(Exception e) {
                setAudioRecorderBtnStatus(mAudioRecorder.getStatus());
                if (mTimer != null) {
                    mTimer.cancel();
                    mTimer = null;
                }
                if (mTimerTask != null) {
                    mTimerTask.cancel();
                    mTimerTask = null;
                }
                ToastUtil.show(getString(R.string.error_audio_recorder, e));
            }
        });
    }

    /**
     * 取消计时，归零
     */
    public void cancelTime() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        mProgressBar.setProgress(0);
        mProgressTime = 0;
    }

    /**
     * 暂停计时
     */
    public void pauseTime() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    /***
     * 重新恢复计时
     */
    public void restartTime() {
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                SingAloneActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //开始计时，每隔一秒钟执行一次
                        mProgressTime += 1000;
                        int progress = (int) (mProgressTime * 1000.0F / MAX_DURATION);
                        mProgressBar.setProgress(progress);
                        mCurrentTime.setText(MusicUtils.makeTimeString(SingAloneActivity.this, mProgressTime / 1000));
                    }
                });
            }
        };
        mTimer.schedule(mTimerTask, 0, 1000);
    }

    /**
     * 停止录制
     */
    protected void stopAudioRecorder() {
        if (isFirst) {
            ToastUtil.show("您还未启动录制哦!");
            return;
        }
        mRecordFilePath = mAudioRecorder.getRecordFileName();
        mAudioRecorder.stop(new AudioRecorder.OnStopListener() {
            @Override
            public void onStop(String activeRecordFileName) {
                pauseTime();
                if (mRecordFilePath != null && FileUtils.isFileExists(mRecordFilePath)) {
                    showPreviewRecordPage(mRecordFilePath);
//                    mAudioRecorder.deleteTempRecordDir();//删除缓存文件
                }
            }

            @Override
            public void onException(Exception e) {

            }
        });
//        mShowRecordingImgView.setVisibility(View.GONE);
        if (mShowRecordingImgView.getBackground() != null && mShowRecordingImgView.getBackground() instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mShowRecordingImgView.getBackground();
            animationDrawable.selectDrawable(0);
            animationDrawable.stop();
        }
    }

    /**
     * 暂停录制
     */
    private void pauseAudioRecorder() {
        mAudioRecorder.pause(new AudioRecorder.OnPauseListener() {
            @Override
            public void onPaused(String activeRecordFileName) {
                pauseTime();
                setAudioRecorderBtnStatus(mAudioRecorder.getStatus());
            }

            @Override
            public void onException(Exception e) {

            }
        });
//        mShowRecordingImgView.setVisibility(View.GONE);
        if (mShowRecordingImgView.getBackground() != null && mShowRecordingImgView.getBackground() instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mShowRecordingImgView.getBackground();
            animationDrawable.selectDrawable(0);
            animationDrawable.stop();
        }
    }


    /**
     * 设置录制按钮状态
     *
     * @param status
     */
    protected void setAudioRecorderBtnStatus(AudioRecorder.Status status) {
        if (status == AudioRecorder.Status.STATUS_UNKNOWN) { //未知状态
            mBtnStartRecorder.setImageResource(R.drawable.ic_record_start);
        } else if (status == AudioRecorder.Status.STATUS_READY_TO_RECORD) { //准备录制
            mBtnStartRecorder.setImageResource(R.drawable.ic_record_start);
        } else if (status == AudioRecorder.Status.STATUS_RECORDING) { //正在录音
            mBtnStartRecorder.setImageResource(R.drawable.ic_record_pause);
        } else if (status == AudioRecorder.Status.STATUS_RECORD_PAUSED) { //暂停录制
            mBtnStartRecorder.setImageResource(R.drawable.ic_record_start);
        }
    }
}
